package com.iflytek.iot.common.log.log2kafka.log.appender;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.iflytek.iot.common.log.log2kafka.log.Log2kafkaQueue;
import com.iflytek.iot.common.log.log2kafka.model.LogModel;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Component;

import java.util.Arrays;


/**
 * @author zurun
 * @date 2020/8/11 18:04:16
 */
@Component
public class MyAppender extends UnsynchronizedAppenderBase {

    private final static Config config = ConfigService.getAppConfig();
    private final static String loggingLevelKey = "logging.level.com.iflytek.iot.platform";
    private final static String loggingLevelDefaultValue = "info,error";
    private final static String loggingLevelValue = config.getProperty(loggingLevelKey, loggingLevelDefaultValue).toUpperCase();

    @Override
    protected void append(Object eventObject) {
        LoggingEvent loggingEvent = (LoggingEvent) eventObject;
        LogModel logBean = new LogModel()
                .setTName(loggingEvent.getThreadName())
                .setTimestamp(String.valueOf(loggingEvent.getTimeStamp()))
                .setLevel(loggingEvent.getLevel().levelStr)
                .setClassName(loggingEvent.getLoggerName())
                .setTraceId(loggingEvent.getMDCPropertyMap().get("traceId"))
                .setMessage(loggingEvent.getFormattedMessage());

        if (filter(logBean)) {
            Log2kafkaQueue.add(logBean);
        } else {
            Log2kafkaQueue.incrementIgnore();
        }
    }

    /**
     * 丢弃flume日志。
     * 丢弃非${value}类型的日志
     * @param logBean logBean
     * @return true or false
     */
    private boolean filter(LogModel logBean) {
        String className = logBean.getClassName();
        if ("logcalLogger".equals(className) || "errLogger".equals(className)) {
            // flume日志丢弃
            return false;
        }
       return Arrays.asList(loggingLevelValue.toUpperCase().split(",")).contains(logBean.getLevel().toUpperCase());
    }
}